/*
 * OracleTableParser.java
 */
package mango.orm.entity.maker;

import java.util.ArrayList;
import java.util.List;

import mango.Mango;
import mango.orm.DaoFactory;
import mango.orm.OrmTypes;
import mango.orm.entity.Entity;


/**
 * 将Oracle数据库中的一个Table转化为一个EOTable
 */
public class OracleTableParser {
    
    static {
        if (!Mango.initialized()) {
            Mango.initialize();
        }
    }
    
    public static EOTable parse(String tableName) {
        String tcolSql = "SELECT column_name, data_type, data_length, data_precision FROM User_Tab_Columns WHERE table_name = ? ORDER BY column_id";
        List<Entity> cols = DaoFactory.c(tcolSql).setParameter(1, tableName.toUpperCase()).listQuery();
        EOTable eotable = new EOTable();
        eotable.setCode(tableName);
        eotable.setComment(tableName);
        eotable.setId(tableName);
        eotable.setName(tableName);
        List<EOColumn> eoCols = new ArrayList<EOColumn>();
        for (Entity col : cols) {
            EOColumn eocol = new EOColumn();
            eocol.setId(col.getString("column_name"));
            eocol.setCode(col.getString("column_name"));
            eocol.setComment(col.getString("column_name"));
            eocol.setLength(col.getString("data_length"));
            eocol.setPrecision(col.getString("data_precision"));
            eocol.setJdbcType(OrmTypes.func1(col.getString("data_type"), eocol.getLength(), eocol.getPrecision()));
            eocol.setJavaType(OrmTypes.func2(col.getString("data_type"), eocol.getLength(), eocol.getPrecision()));
            eoCols.add(eocol);
        }
        eotable.setColumns(eoCols);
        String keyColSql = "SELECT constraint_name, column_name FROM User_Cons_Columns WHERE constraint_name=(SELECT constraint_name FROM User_Constraints WHERE constraint_type='P' AND table_name=?) ORDER BY POSITION";
        List<Entity> keycols = DaoFactory.c(keyColSql).setParameter(1, tableName.toUpperCase()).listQuery();
        EOKey eokey = new EOKey();
        for (Entity key : keycols) {
            eokey.setId(key.getString("constraint_name"));
            eokey.setCode(key.getString("constraint_name"));
            eokey.setName(key.getString("constraint_name"));
            eokey.addColumn(key.getString("column_name"));
        }
        eotable.addKey(eokey);
        eotable.setPrimaryKey(eokey.getId());
        return eotable;
    }
}
